﻿#region License
// Copyright (c) 2009 Shun Chi Guo
// E-Mail:shuncy@gmail.com
// Blog:http://shuncy.cnblogs.com
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace shun.PAPLib.Request
{
    /// <summary>
    /// 推送消息包结构
    /// </summary>
    public class PushMessage : IRequest
    {
        PushObject pushObject;
        public PushMessage(PushObject pushObj)
        {
            pushObject = pushObj;
            //取得新的流水ID
            PushID = GetPushID();
            pushObject.PushID = PushID;

            if (pushObject.ContentType == "si")
            {
                this.ContentHead = NewLine + "--" + Boundary + NewLine + "Content-Type: text/vnd.wap.si" + NewLine + NewLine;
            }
            else
            {
                this.ContentHead = NewLine + "--" + Boundary + NewLine + "Content-Type: text/vnd.wap.sl" + NewLine + NewLine;
            }
        }

        protected override void ControlBody(XmlWriter xml)
        {
            //创建push-message节点
            xml.WriteStartElement("push-message");
            //push_id属性
            xml.WriteAttributeString("push-id", pushObject.PushID);
            //replace-push-id替换消息ID，为以前发送消息的ID
            if (!String.IsNullOrEmpty(pushObject.ReplacePushID))
            {
                xml.WriteAttributeString("replace-push-id", pushObject.ReplacePushID);
                //replace-method,可选值为pending-only,all
                xml.WriteAttributeString("replace-method", pushObject.ReplaceMethod);
            }

            //deliver-before-timestamp必须发送到终端的时间，超过则不继续进行，格式YYYY-MM-DDThh:mm:ssZ 
            if (pushObject.DeliverBeforeTimestamp != null && pushObject.DeliverBeforeTimestamp > DateTime.Now.AddMinutes(-10))
            {
                xml.WriteAttributeString("deliver-before-timestamp", pushObject.DeliverBeforeTimestamp.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
            }
            //deliver-after-timestamp在指定的时间才能发送，定时时间，格式YYYY-MM-DDThh:mm:ssZ 
            if (pushObject.DeliverAfterTimestamp != null && pushObject.DeliverAfterTimestamp > DateTime.Now.AddMinutes(-10))
            {
                xml.WriteAttributeString("deliver-after-timestamp", pushObject.DeliverAfterTimestamp.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
            }

            //source-reference内容提供者的文本名称
            if (!String.IsNullOrEmpty(pushObject.SourceReference))
            {
                xml.WriteAttributeString("source-reference", pushObject.SourceReference);
            }
            //ppg-notify-requested-to程序提供的通知接收地址
            if (!String.IsNullOrEmpty(pushObject.PpgNotifyRequestedTo))
            {
                xml.WriteAttributeString("ppg-notify-requested-to", pushObject.PpgNotifyRequestedTo);
            }
            //progress-notes-requested通知PPG是否想收到进程的日志消息,如果设置true则会在结果包中包含日志信息
            xml.WriteAttributeString("progress-notes-requested", pushObject.ProgressNotesRequested ? "true" : "false");

            //创建接收地址信息,循环生成
            foreach (string add in pushObject.Address)
            {
                xml.WriteStartElement("address");
                xml.WriteAttributeString("address-value", add);
                xml.WriteEndElement();
            }

            //quality-of-service创建网络信息节点
            xml.WriteStartElement("quality-of-service");
            //priority 优先级，有三种:high | medium | low
            xml.WriteAttributeString("priority", pushObject.QualityObj.Priority);
            //delivery-method投递方式，支持四种confirmed | preferconfirmed| unconfirmed | notspecified
            if (!String.IsNullOrEmpty(pushObject.QualityObj.DeliveryMethod))
            {
                xml.WriteAttributeString("delivery-method", pushObject.QualityObj.DeliveryMethod);
            }
            //network网络类型
            xml.WriteAttributeString("network", pushObject.QualityObj.Network);

            //network-required是否指定网络类型
            xml.WriteAttributeString("network-required", pushObject.QualityObj.NetworkRequire ? "true" : "false");
            //bearer标志传输消息时要求承载的类型
            xml.WriteAttributeString("bearer", pushObject.QualityObj.Beare);
            //bearer-required是否指定承载类型true,false
            xml.WriteAttributeString("bearer-required", pushObject.QualityObj.BeareRequire ? "true" : "false");
            //quality-of-service结束
            xml.WriteEndElement();
            //push-message结束
            xml.WriteEndElement();
        }

        protected override void ContentBody(XmlWriter xml)
        {
            xml.WriteStartDocument();
            pushObject.ContentType = pushObject.ContentType.ToLower().Trim();
            //添加申明信息
            if (pushObject.ContentType == "si")
            {
                //http://www.wapforum.org/DTD/si.dtd
                xml.WriteDocType("si", "-//WAPFORUM//DTD SI 1.0//EN", "http://www.wapforum.org/DTD/si.dtd", null);
                //连接开始
                xml.WriteStartElement("si");

                //indication节点
                xml.WriteStartElement("indication");
                //href超连接地址
                xml.WriteAttributeString("href", pushObject.Url);
                //action动作
                xml.WriteAttributeString("action", "signal-medium");
                //si-id客户端显示的发送地址
                if (!String.IsNullOrEmpty(pushObject.SIID))
                {
                    xml.WriteAttributeString("si-id", pushObject.SIID);
                }
                //created 创建日期

                //si-expires过期日期

                //连接文本
                xml.WriteValue(pushObject.Content);
                xml.WriteEndElement();

                //info节点

                //连接结束
                xml.WriteEndElement();
            }
            else
            {
                xml.WriteDocType("sl", "-//WAPFORUM//DTD SL 1.0//EN", "http://www.wapforum.org/DTD/sl.dtd", null);
                xml.WriteStartElement("sl");
                //href超连接地址
                xml.WriteAttributeString("href", pushObject.Url);
                //action动作
                xml.WriteAttributeString("action", "execute-low");
                xml.WriteEndElement();
            }
        }

        protected override void CapabilitiesBody(XmlWriter xml)
        {
            throw new NotImplementedException();
        }

        protected override bool ProcContent
        {
            get
            {
                return true;
            }
        }

        protected override bool ProcCapabilities
        {
            get
            {
                return false;
            }
        }
    }
}
